import {post, fetch} from '../../../utils/axios'

const state = {
  name: '新增服务',
  type: {},
  dialog: false,
  status: {},
  fields: {},
  env: {},
  OutterIpSource: {},
  host: {},
  valid: null,
  nameRules: [
    (v) => !!v || '请输入服务名'
  ],
  innerIpRules: [
    (v) => !!v || '请输入内网地址'
  ],
  typeRules: [
    (v) => !!v || '请输选择类型'
  ],
  statusRules: [
    (v) => v !== undefined || '请输选择状态'
  ],
  envRules: [
    (v) => !!v || '请输选择环境'
  ],
  msg: {
    innerIp: ''
  }
}

const mutations = {
  closeNewService: (state, payload) => {
    state.dialog = false
  },
  saveService (state, payload) {
    if (payload.validate()) {
      post('/service/',
        state.fields
      ).then((response) => {
        state.dialog = false
      }).catch((error) => {
        if (error.response.data) {
          let datas = error.response.data
          for (var name in datas) {
            state.msg[name] = datas[name]
            console.log(state.msg)
          }
        }
      })
    }
  },
  newServiceDialog (state, payload) {
    payload.reset()
    let msg = state.msg
    for (var i in msg) {
      msg[i] = ''
    }
  },
  loadServiceSelect (state) {
    state.type = this._vm.$data.$$state.listservice.type
    state.status = this._vm.$data.$$state.listservice.status
    state.env = this._vm.$data.$$state.listservice.env
    state.OutterIpSource = this._vm.$data.$$state.listservice.OutterIpSource
  },
  serviceEnv (state) {
    state.fields.host = []
    state.host = {items: [{ text: '', value: '' }]}
    fetch('/service/get_host/', {
      env: state.fields.env
    }).then((response) => {
      let res = JSON.parse(response)
      state.host.items = res.host
    }).catch((error) => {
      state.etext = error.response
    })
  }
}

const actions = {
  closeNewService ({commit}) {
    commit('closeNewService')
  },
  saveService ({commit}, payload) {
    commit('saveService', payload)
  },
  newServiceDialog ({commit, state}, payload) {
    commit('newServiceDialog', payload)
    if (!state.dialog) {
      this.dispatch('listservice/handlerService')
    }
  },
  loadServiceSelect ({commit}) {
    commit('loadServiceSelect')
  },
  serviceEnv ({commit}) {
    commit('serviceEnv')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
